from .globals import g


def elements_format(data):
    elements = {}
    for d in data:
        # elements[f"{d['page']}-{d['element']}"] = d
        elements[d['element_id']] = d
    return elements


class Elements:
    def __init__(self):
        pass

    def env(self):
        pass

    def get_elements(self, element_define):
        self.elements = elements_format(element_define)

    def have(self, page, element):
        ele = element.split('#')

        if len(ele) >= 2:
            _el = ele[0] + '#'
        else:
            _el = element
        # 如果有<>,则不判断了
        if '<' in _el:
            return '', '通用' + '-' + element
        # 在元素定位表中查询
        elem = page + '-' + _el
        if self.elements.get(elem, ''):
            return self.elements[elem]['custom'], page + '-' + element
        else:
            # 查不到就在通用里查,还是查不到，可能是不在 element.xlsx 中定义的元素
            elem = '通用' + '-' + _el
            if self.elements.get(elem, ''):
                return self.elements[elem]['custom'], '通用' + '-' + element
            else:
                # logger.info('Page:%s element:%s' % (page, element))
                return '', element

    def get(self, element):
        el = self.elements.get(element)
        if not el:
            return None
        value = el.get('value')
        return el, value

    def replace_variable(self, element):
        e = self.elements.get('element')
        if e:
            self.elements[element]['value'] = e['value'].format(**g.var)


e = Elements()
